package cn.mumzone.pos.ui.widgets;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.Shader;
import android.os.Build;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;

import cn.mumzone.basic.util.BigDecimalUtil;
import cn.mumzone.pos.R;

/**
 * Created By Dlx
 * on 2019/7/13
 *
 * 默认不显示文字，只显示百分比，如果需要显示文字，
 * 请设置{#fun}
 */
public class RocketProgressView extends android.support.v7.widget.AppCompatTextView {
    private Paint mTextPaint;
    private float mProgressPercent = 0.0f;
    private Paint bgPaint;
    private Bitmap bitmap;
    private boolean showTextFlag = false;

    public RocketProgressView(Context context) {
        super(context);
        init();
    }

    public RocketProgressView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();

    }

    public RocketProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();

    }


    @Override
    protected void onDraw(Canvas canvas) {

        int middle = (int) (mProgressPercent * getWidth());
        bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_rocket);
        drawBg(canvas);
        drawProgress(canvas);
        // 绘制变色的区域
        drawText(canvas, Color.WHITE, 0, middle);

        // 绘制不变色区域
        drawText(canvas, Color.BLACK, middle, getWidth());
    }

    private void init() {


        //设置文字画笔
        mTextPaint = new Paint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextSize(50);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            //解决文字有时候画不出问题
            setLayerType(LAYER_TYPE_SOFTWARE, mTextPaint);
        }
    }

    public void setPercent(float currentPercent) {
        if (currentPercent >= 1.0f) {
            currentPercent = 1.0f;
        }
        mProgressPercent = currentPercent;
        invalidate();
    }

    public void showText(boolean tof) {
        showTextFlag = tof;
    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void drawBg(Canvas canvas) {

        bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        bgPaint.setStrokeCap(Paint.Cap.BUTT);
        bgPaint.setColor(Color.parseColor("#F0F0F0"));
        canvas.drawRoundRect(0, 0, getWidth(), getHeight(), getHeight() / 2, getHeight() / 2, bgPaint);
    }


    private Bitmap createTextBitmap(int color, String text) {

        TextPaint textPaint = new TextPaint();
        textPaint.setAntiAlias(true);
        textPaint.setTextSize(getTextSize());
        Bitmap newBitmap = Bitmap.createBitmap((int) textPaint.measureText(text), (int) (textPaint.getFontMetrics().descent - textPaint.getFontMetrics().ascent), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        canvas.drawBitmap(newBitmap, 0, 0, null);
        StaticLayout sl = new StaticLayout(text, textPaint, newBitmap.getWidth(), Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
        sl.draw(canvas);


        return newBitmap;

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void drawProgress(Canvas canvas) {
        bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        bgPaint.setStrokeCap(Paint.Cap.BUTT);
        bgPaint.setColor(Color.parseColor("#F0F0F0"));


        if (getWidth() * mProgressPercent <= getHeight()) {
            canvas.save();
            Path path = new Path();
            path.addCircle(getHeight() / 2, getHeight() / 2, getHeight() / 2, Path.Direction.CW);
            canvas.clipPath(path);
            Shader shader = new LinearGradient(0, getHeight() / 2, getWidth() * mProgressPercent, getHeight() / 2, new int[]{Color.parseColor("#67676A"), Color.parseColor("#28282C")}, null, Shader.TileMode.CLAMP);
            bgPaint.setShader(shader);
            canvas.drawCircle(-getHeight() / 2 + getWidth() * mProgressPercent, getHeight() / 2, getHeight() / 2, bgPaint);
            canvas.restore();

            canvas.save();
            canvas.scale(1.3f, 1.3f, getWidth() * mProgressPercent, (getHeight() / 2));
            canvas.drawBitmap(bitmap, getWidth() * mProgressPercent + 20, (getHeight() / 2) - (bitmap.getHeight() / 2), bgPaint);
            canvas.restore();

        } else {

            String text = showTextFlag ? getText().toString() : BigDecimalUtil.getStringNumberFromFloat(mProgressPercent * 100f) + "%";
            Rect textBounds = new Rect();
            mTextPaint.getTextBounds(text, 0, text.length(), textBounds);
            Paint.FontMetricsInt metrics = mTextPaint.getFontMetricsInt();

            // 获取起始位置
            int x = getWidth() / 2 - textBounds.width() / 2;
            int y = getHeight() / 2 + (metrics.bottom - metrics.top) / 2 - metrics.bottom;

            int x1 = getWidth() / 2 + textBounds.width() / 2;
            // 火箭触及文字
            if (bitmap.getWidth() * 1.3f + 20 + getWidth() * mProgressPercent > x && 20 + getWidth() * mProgressPercent < x1) {
                Bitmap textBitmap = createTextBitmap(Color.BLACK, text);
                int saved = canvas.saveLayer(null, null, Canvas.ALL_SAVE_FLAG);
                PorterDuffXfermode xfermode = new PorterDuffXfermode(PorterDuff.Mode.XOR);
                canvas.drawBitmap(textBitmap, getWidth() / 2 - textBitmap.getWidth() / 2, getHeight() / 2 - textBitmap.getHeight() / 2, mTextPaint); // 画方
                mTextPaint.setXfermode(xfermode); // 设置 Xfermode
                canvas.save();
                canvas.scale(1.3f, 1.3f, getWidth() * mProgressPercent, (getHeight() / 2));
                canvas.drawBitmap(bitmap, getWidth() * mProgressPercent + 20, (getHeight() / 2) - (bitmap.getHeight() / 2), mTextPaint);
                canvas.restore();
                mTextPaint.setXfermode(null); // 用完及时清除 Xfermode
                canvas.restoreToCount(saved);
            } else {
                canvas.save();
                canvas.scale(1.3f, 1.3f, getWidth() * mProgressPercent, (getHeight() / 2));
                canvas.drawBitmap(bitmap, getWidth() * mProgressPercent + 20, (getHeight() / 2) - (bitmap.getHeight() / 2), bgPaint);
                canvas.restore();

            }
            Shader shader = new LinearGradient(0, getHeight() / 2, getWidth() * mProgressPercent, getHeight() / 2, new int[]{Color.parseColor("#67676A"), Color.parseColor("#28282C")}, null, Shader.TileMode.CLAMP);
            bgPaint.setShader(shader);
            canvas.drawRoundRect(0, 0, getWidth() * mProgressPercent, getHeight(), getHeight() / 2, getHeight() / 2, bgPaint);

        }
    }

    private void drawText(Canvas canvas, int colorInt, int start, int end) {


        mTextPaint.setTextSize(getTextSize());
        mTextPaint.setColor(colorInt);

        // 保存当前画布状态
        canvas.save();

        Rect rect = new Rect(start, 0, end, getHeight());
        canvas.clipRect(rect);

        // 获取文字的基本宽高信息
        String text = showTextFlag ? getText().toString() : BigDecimalUtil.getStringNumberFromFloat(mProgressPercent * 100f) + "%";
        Rect textBounds = new Rect();
        mTextPaint.getTextBounds(text, 0, text.length(), textBounds);
        Paint.FontMetricsInt metrics = mTextPaint.getFontMetricsInt();

        // 获取起始位置
        int x = getWidth() / 2 - textBounds.width() / 2;
        int y = getHeight() / 2 + (metrics.bottom - metrics.top) / 2 - metrics.bottom;

        int x1 = getWidth() / 2 + textBounds.width() / 2;
//        canvas.drawText(text, x, y, paint);

        if (bitmap.getWidth() * 1.3f + 15 + getWidth() * mProgressPercent > x &&
                20 + getWidth() * mProgressPercent < x1) {
            if (start == 0 && end != 0) {
                canvas.drawText(text, -textBounds.left + x, -textBounds.top + (getHeight() / 2 - textBounds.height() / 2), mTextPaint);
                canvas.restore();
            }
            return;
        }
        canvas.drawText(text, -textBounds.left + x, -textBounds.top + (getHeight() / 2 - textBounds.height() / 2), mTextPaint);

        // 清空画布属性，方便接下来绘制变色的部分
        canvas.restore();

    }
}
